package com.qin.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qin.entity.BookCategory;
import com.qin.service.BookCategoryService;
import com.qin.service.impl.BookCategoryServiceImpl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
/**
 * 负责根据一级菜单的id，查询到它们的子级菜单以及子子菜单
 */
@WebServlet("/getcategory")
public class GetCategoryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BookCategoryService bookCategoryService = new BookCategoryServiceImpl();
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		StaticLog.debug("开始获取当前一级菜单的二级菜单及其子菜单信息");
		// 拿到要查询其子菜单的id的JSON字符串
		String stringCategoryId = request.getParameter("bookCategoryId");
		
		StaticLog.debug("要分析的JSON字符串：{}", stringCategoryId);
		// 把JSON字符串转换成数组
		JSONArray parseArray = JSONUtil.parseArray(stringCategoryId);
		
		// 准备List，用来放二级分类和它的子分类
		List<BookCategory> myBookCategory = new ArrayList<>();
				
		// 遍历这个JSON字符串
		for (int i = 0; i < parseArray.size(); i++) {
			Long id = parseArray.getLong(i);
			// 根据传过来的id查询二级分类
			List<BookCategory> bookCategory = bookCategoryService.queryBookCategoryByPId(id);
			
			// 遍历，设置二级分类的子分类
			if(bookCategory!=null) {
				for (BookCategory bc : bookCategory) {
					List<BookCategory> children = bookCategoryService.queryBookCategoryByPId(bc.getId());
					bc.setChildren(children);
				}
			}
			StaticLog.debug("要查询的Id是{}，得到图书分类：{}", id,bookCategory);
			// 放入List
			myBookCategory.addAll(bookCategory);
		}
		
		// 转成JSON字符串
		String parse = JSONUtil.toJsonStr(myBookCategory);
		
		// 发送
		response.getWriter().print(parse);
	}

}
